// import express from "express";
// import db from "./../libs/DBhelper/index";

// const apiroute = express.Router(); //创建一个保安大爷
// //这个保安大爷,管理ApiRoute.js 里的方法
// //api大楼里有 login公司
// apiroute.get("/login", (request, response, next) => {
//     response.end("login,我是真的login");
// })
// //api大楼里有 reg公司
// apiroute.post("/reg", (request, response, next) => {
//     //准备sql语句
//     let sql = "INSERT INTO user (u_name,u_pwd,u_phone,u_email)VALUES (?,?,?,?) ;";
//     //接收到前端传递过来的数据
//     let params = [request.body.uname, request.body.upwd, request.body.uphone, request.body.uemail]
//     //执行sql语句
//     db.exec(sql, params, (err, result, fields) => {

//         if (err) {
//             response.json({
//                 msg: "用户名已存在",
//                 err: err.message,
//                 status: -1
//             });
//             return;
//         }
//         //affectedRows 受影响行数 如果1 表示成功
//         if (result.affectedRows == 1) {
//             response.json({
//                 msg: "注册成功",
//                 status: 1
//             });
//         } else {
//             response.json({
//                 msg: "注册失败",
//                 status: -2
//             });
//         }

//     })
// })

// // api/login post
// apiroute.post("/login", (request, response, next) => {

//     let sql = "SELECT `u_name`,`u_phone`,`u_email` FROM user ";
//     sql += "WHERE (u_name=? AND u_pwd=?)  OR (u_phone=? AND u_pwd=?);"; //

//     let params = [request.body.uname,
//     request.body.upwd,
//     request.body.uphone,
//     request.body.upwd
//     ]
//     db.execSync(sql, params).then((result, fields) => {
//         console.log(result, fields);

//         if (result.length >= 1) {
//             response.json({
//                 msg: "登录成功",
//                 status: 101,
//                 data: result[0]
//             });
//         } else {
//             response.json({
//                 msg: "登录失败，用户名或密码错误",
//                 status: -101,
//             });
//         }
//     })
// })

// //ES7   如果希望像同步一样写异步,就在函数的前面加上 await,在await所在的函数,加async
// apiroute.post("/login2", async (request, response, next) => {

//     let sql = "SELECT `u_name`,`u_phone`,`u_email` FROM user ";
//     sql += "WHERE (u_name=? AND u_pwd=?)  OR (u_phone=? AND u_pwd=?);"; //

//     let params = [request.body.uname,
//     request.body.upwd,
//     request.body.uphone,
//     request.body.upwd
//     ]

//     // await 后边必须接Promise对象 同步的异步 ,用Promse + async+ await
//     let result = await db.execSync(sql, params);

//     var resultJSON = {
//         msg: "登录失败,用户名或密码错误",
//         status: -1
//     }
//     if (result.length >= 1) {
//         resultJSON["msg"] = "登录成功";
//         resultJSON["status"] = 1;
//         resultJSON["data"] = result[0]
//     }
//     response.json(resultJSON)

// })


// //加载所有产品
// apiroute.get("/goods", (request, response, next) => {

//     let params = request.query;
//     //1.先读取所有的产品
//     var goodsStr = fs.readFileSync("./data/goods.json");
//     var goodsArr = JSON.parse(goodsStr);

//     //如果有参数,就根据传递古来的参数显示某一个产品
//     if (params.gid != undefined) {
//         var newArr = goodsArr.filter((el, index) => {
//             return el.gid == params.gid
//         });

//         response.json(newArr)

//     } else {

//         response.json(goodsArr)
//     }
//     //否则就显示所有的产品
// })

// //加入购物车
// apiroute.post("/addcart", async (request, response, next) => {


//     let sqlQuery = " SELECT *FROM `carts` WHERE u_name=? AND c_name=? ;";
//     let paramsQuery = [
//         request.session["users"].u_name,
//         request.body.gname,
//     ]
//     //先查询,如果有,就做修改,如果没有做插入
//     var resultQuery = await db.execSync(sqlQuery, paramsQuery)
//     if (resultQuery.length >= 1) { //已经购买了
//         let sqlUpdate = "UPDATE carts SET c_num=c_num+? , c_total= c_num*c_price WHERE u_name=? AND c_name=? ;";

//         let pramasUpdate = [
//             request.body.num,
//             request.session["users"].u_name,
//             request.body.gname
//         ]

//         var resultUpdate = await db.execSync(sqlUpdate, pramasUpdate);

//         response.json({
//             msg: "加入购车成功u",
//             status: 2
//         });

//     } else {
//         // {gid: 1, gname: "95新苹果6s 64G", gprice: 1049, gimgs1: "./images/1_1.jpg", num: 1}
//         let sqlInsert = "INSERT INTO carts (c_name,c_price,c_num,c_total,c_img,u_name)VALUES (?,?,?,?,?,?);";
//         let pramasInert = [
//             request.body.gname,
//             request.body.gprice,
//             request.body.num,
//             request.body.gprice * request.body.num,
//             request.body.gimgs1,
//             request.session["users"].u_name
//         ]
//         const result = await db.execSync(sqlInsert, pramasInert);
//         response.json({
//             msg: "加入购车成功i",
//             status: 1
//         });
//     }

// })


// apiroute.get("/carts", async (request, response, next) => {

//     var query = 'SELECT *FROM `carts` WHERE u_name=?;';
//     var parmas = [
//         request.session["users"].u_name
//     ]
//     var result = await db.execSync(query, parmas);
//     response.json(result);
// })


// apiroute.post("/changecarts", async function (request, response, next) {
//     let sql = "UPDATE carts SET c_num=? , c_total= c_num*c_price WHERE c_id=?";

//     let params = [request.body.num, request.body.cid];
//     var result = await db.execSync(sql, params);

//     response.json({
//         msg: "查询成功",
//         status: 1,
//         data: result
//     })
// })

// //删除购物车
// apiroute.post("/delete", async (request, response, next) => {
//     let sql = "DELETE FROM carts WHERE c_id= ? ;";
//     let params = [request.body.cid];

//     var result = await db.execSync(sql, params);
//     if (result.affectedRows == 1) {

//         response.json({
//             msg: "删除成功",
//             status: 1
//         })
//     } else {
//         response.json({
//             msg: "删除失败",
//             status: -1
//         })
//     }

// })



// //暴露保安大爷
// //直接把保安大爷当做对象 往外暴露
// module.exports = apiroute




import express from "express";
import db from "./../libs/DBhelper/";
import fs from "fs";

const apiroute = express.Router(); //创建一个保安大爷
//这个保安大爷,管理ApiRoute.js 里的方法
//api大楼里有 login公司
apiroute.get("/login", (request, response, next) => {
    response.end("login,我是真的login");


})
//api大楼里有 reg公司
apiroute.post("/reg", (request, response, next) => {
    //准备sql语句
    let sql = "INSERT INTO user (u_name,u_pwd,u_phone,u_email)VALUES (?,?,?,?) ;";
    //接收到前端传递过来的数据
    let params = [request.body.uname, request.body.upwd, request.body.uphone, request.body.uemail]
    //执行sql语句
    db.exec(sql, params, (err, result, fields) => {

        if (err) {
            response.json({
                msg: "执行sql异常",
                err: err.message,
                status: -1
            });
            return;
        }
        //affectedRows 受影响行数 如果1 表示成功
        if (result.affectedRows == 1) {
            response.json({
                msg: "注册成功",
                status: 1
            });
        } else {
            response.json({
                msg: "注册失败",
                status: -2
            });
        }

    })
})

// api/login post
apiroute.post("/login", (request, response, next) => {

    let sql = "SELECT `u_name`,`u_phone`,`u_email` FROM user WHERE (u_name=? AND u_pwd=?);";
    //sql += ""; //

    let params = [request.body.uname,
        request.body.upwd,
        request.body.uphone,
        request.body.upwd
    ]
    console.log(sql);
    db.execSync(sql, params).then((result, fields) => {

        if (result.length >= 1) {
            //如果登录成功了,就把当前登录人的信息保存到session中
            request.session["users"] = JSON.parse(JSON.stringify(result[0]));
            response.json({
                msg: "登录成功",
                status: 101,
                data: result[0]
            });
        } else {
            response.json({
                msg: "登录失败",
                status: -101,
            });
        }
    })
})

//ES7   如果希望像同步一样写异步,就在函数的前面加上 await,在await所在的函数,加async
apiroute.post("/login2", async (request, response, next) => {

    let sql = "SELECT `u_name`,`u_phone`,`u_email` FROM user ";
    sql += "WHERE (u_name=? AND u_pwd=?)  OR (u_phone=? AND u_pwd=?);"; //

    let params = [request.body.uname,
        request.body.upwd,
        request.body.uphone,
        request.body.upwd
    ]

    // await 后边必须接Promise对象 ,像同步的异步 ,用Promse + async+ await
    let result = await db.execSync(sql, params);

    var resultJSON = {
        msg: "登录失败",
        status: -201
    }
    if (result.length >= 1) {
        resultJSON["msg"] = "登录成功";
        resultJSON["status"] = 201;
        resultJSON["data"] = result[0]
    }
    response.json(resultJSON)

})


//加载所有产品
apiroute.get("/goods", (request, response, next) => {

    let params = request.query;
    //1.先读取所有的产品
    var goodsStr = fs.readFileSync("./data/goods.json");
    var goodsArr = JSON.parse(goodsStr);

    //如果有参数,就根据传递古来的参数显示某一个产品
    if (params.gid != undefined) {
        var newArr = goodsArr.filter((el, index) => {
            return el.gid == params.gid
        });

        response.json(newArr)

    } else {

        response.json(goodsArr)
    }
    //否则就显示所有的产品
})

//加入购物车
apiroute.post("/addcart", async (request, response, next) => {
    // console.log(111111111111111111111);

    let sqlQuery = " SELECT *FROM `carts` WHERE u_name=? AND c_name=? ;";
    let paramsQuery = [
        request.session["users"].u_name,
        request.body.gname,
    ]
    //先查询,如果有,就做修改,如果没有做插入
    var resultQuery = await db.execSync(sqlQuery, paramsQuery)
    if (resultQuery.length >= 1) { //已经购买了
        let sqlUpdate = "UPDATE carts SET c_num=c_num+? , c_total= c_num*c_price WHERE u_name=? AND c_name=? ;";
        // console.log(sqlUpdate);
        let pramasUpdate = [
            request.body.num,
            request.session["users"].u_name,
            request.body.gname
        ]
        // console.log(request.session["users"].u_name);
        var resultUpdate = await db.execSync(sqlUpdate, pramasUpdate);

        response.json({
            msg: "加入购物车成功",
            status: 2
        });

    } else {
        // {gid: 1, gname: "95新苹果6s 64G", gprice: 1049, gimgs1: "./images/1_1.jpg", num: 1}
        let sqlInsert = "INSERT INTO carts (c_name,c_price,c_num,c_total,c_img,u_name)VALUES (?,?,?,?,?,?);";
        let pramasInert = [
            request.body.gname,
            request.body.gprice,
            request.body.num,
            request.body.gprice * request.body.num,
            request.body.gimgs1,
            request.session["users"].u_name
        ]
        // console.log(request.session["users"].u_name);
        const result = await db.execSync(sqlInsert, pramasInert);
        response.json({
            msg: "加入购物车成功",
            status: 1
        });
    }

})


apiroute.get("/carts", async (request, response, next) => {

    var query = 'SELECT *FROM `carts` WHERE u_name=?;';
    var parmas = [
        request.session["users"].u_name
    ]
    console.log(query);
    console.log("carts:"+request.session["users"].u_name);
    var result = await db.execSync(query, parmas);
    console.log(result);
    response.json(result);
})


apiroute.post("/changecarts", async function (request, response, next) {
    let sql = "UPDATE carts SET c_num=? , c_total= c_num*c_price WHERE c_id=?";

    let params = [request.body.num, request.body.cid];
    var result = await db.execSync(sql, params);

    response.json({
        msg: "查询成功",
        status: 1,
        data: result
    })
})

//删除购物车
apiroute.post("/delete", async (request, response, next) => {
    let sql = "DELETE FROM carts WHERE c_id= ? ;";
    let params = [request.body.cid];

    var result = await db.execSync(sql, params);
    if (result.affectedRows == 1) {

        response.json({
            msg: "删除成功",
            status: 1
        })
    } else {
        response.json({
            msg: "删除失败",
            status: -1
        })
    }

})

//退出登录
apiroute.get("/quitLogin", async (request, response, next) => {
    window.localStorage.currentUser = "";
    response.json({
        msg: "退出成功",
        status: 1
    })
})
// apiroute.get("/quitLogin", async (request, response, next) => {
//     window.localStorage = null;
//     // response.clearCookie();
//     console.log("quitLogin");
//     response.json({
//         msg: "退出成功",
//         status: 1
//     })
// })




//暴露保安大爷
//直接把保安大爷当做对象 往外暴露
module.exports = apiroute